package com.thirtydays.frame.ui.edittext

import android.content.Context
import android.text.InputFilter
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.widget.addTextChangedListener
import com.thirtydays.frame.R
import com.thirtydays.frame.databinding.ChildCodeViewBinding
import com.thirtydays.frame.databinding.VerifyCodeViewBinding


/**
 * @author 小垚
 * @创建时间： 2021/4/21
 * @描述：验证码界面
 **/
class VerifyCodeView : RelativeLayout {
    constructor(context: Context) : super(context) {
        initView(context, null, -1, -1)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initView(context, attrs, -1, -1)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView(context, attrs, defStyleAttr, -1)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        initView(context, attrs, defStyleAttr, defStyleRes)
    }

    private var views = mutableListOf<ChildCodeViewBinding>()
    lateinit var viewBinding: VerifyCodeViewBinding
    lateinit var inputComplete: (String) -> Unit
    private var maxLength = 0
    private fun initView(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
        viewBinding = VerifyCodeViewBinding.inflate(LayoutInflater.from(context), this, true)

        viewBinding.codeEt.isCursorVisible = false
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.VerifyCodeView)
        maxLength = attributes.getInteger(R.styleable.VerifyCodeView_codeLength, 6)

        viewBinding.codeEt.filters = arrayOf(InputFilter.LengthFilter(maxLength))

        for (index in 0 until maxLength) {
            val inflate = ChildCodeViewBinding.inflate(LayoutInflater.from(context), viewBinding.content, true)
            inflate.root.layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT).apply {
                weight = 1f
            }
            views.add(inflate)
        }

        viewBinding.codeEt.addTextChangedListener { edit ->
            edit?.let {
                if (it.length >= maxLength) {
                    if (this::inputComplete.isInitialized) {
                        inputComplete(it.toString())
                    }
                }

                for (index in 0 until maxLength) {
                    if (index < edit.length) {
                        views[index].codeAtv.text = it.toString().toCharArray()[index].toString()
                    } else {
                        views[index].codeAtv.text = ""
                    }
                }
            }
        }
    }


}